<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品图号" prop="drawingNumber">
        <el-input
          v-model="queryParams.drawingNumber"
          placeholder="请输入产品图号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品规格" prop="productStandard">
        <el-input
          v-model="queryParams.productStandard"
          placeholder="请输入产品规格"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="启用时间" prop="activeData">
        <el-date-picker
          v-model="activeData"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="停用时间" prop="stopData">
        <el-date-picker
          v-model="stopData"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="btnWrap">
      <div>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['config:material-history:export']"
        >
          数据导出
        </el-button>
      </div>
      <div>
        <el-button
          type="primary"
          @click="openTableTitleSet"
        >
          表头设置
        </el-button>
      </div>
    </div>
    <Table
      :columns="tableTitleList"
      :selection="tableObject.tableList.length ? true : false"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      @register="register"
      border
      :tableHeight="tableHeight"
    >
      <template #action="{ row }">
        <el-button
          link
          type="primary"
          v-hasPermi="['config:material-history:view']"
          @click="openForm(row.id)"
        >
          查看
        </el-button>
      </template>
    </Table>
  </ContentWrap>

  <!-- 表头设置 -->
  <table-width-set ref="tableTitleSet" @refresh="getTableTitle" />
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
</template>

<script setup lang="ts" name="MaterialHistory">
import download from '@/utils/download'
import * as MaterialHistoryApi from '@/api/config/materialHistory'
import type { CrudSchema } from '@/hooks/web/useCrudSchemas'

const { push } = useRouter()

const queryParams = reactive({
  pageNo: 1,
  productNumber: null,
  productName: null,
  drawingNumber: null,
  productStandard: null,
  activeData: undefined,
  stopData: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const activeData = ref([])
const stopData = ref([])

const tableTitleList = ref<CrudSchema[]>([]) // 表头列表
const code = 'MaterialHistory'  //表头名
const tableHeight = ref(0)

// tableObject：表格的属性对象，可获得分页大小、条数等属性
// tableMethods：表格的操作对象，可进行获得分页、删除记录等操作
const { tableObject, tableMethods } = useTable({
  getListApi: MaterialHistoryApi.getMaterialHistoryPage, // 分页接口
  defaultParams: queryParams
})

const parentRef = ref()
// 获取table组件
const register = (parent: any) => {
  parentRef.value = parent
}

// 获得表格的各种操作
const { getList, setSearchParams } = tableMethods

// 获取表头
const getTableTitle = async () => {
  const res = await MaterialHistoryApi.getMaterialHistoryPage(queryParams)
  res.labels.push({
    field: 'action',
    label: '操作',
    align: 'left',
    headerAlign: 'left',
    width: 80
  })
  const { allSchemas } = useCrudSchemas(res.labels)
  tableTitleList.value = allSchemas.tableColumns
}

// 打开表头设置
const tableTitleSet = ref()
const openTableTitleSet = () => {
  tableTitleSet.value.open(tableTitleList.value, code)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  queryParams.activeData = activeData.value ? JSON.parse(JSON.stringify(activeData.value)).join(',') : ''
  queryParams.stopData = stopData.value ? JSON.parse(JSON.stringify(stopData.value)).join(',') : ''
  setSearchParams(queryParams)
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  activeData.value = []
  stopData.value = []
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (id: number) => {
  push(`/config/config/materiel/materialHistoryDetail?id=${id}`)
}

/** 导出按钮操作 */
const exportRef = ref()
const handleExport = async () => {
  exportRef.value.open()
}

// 下载
const downloadFun = async () => {
  const val = exportRef.value.params
  let params = {
    fileName: val.name,
    ids: []
  }
  if (val.range === 'all') {
    params.ids = []
  } else {
    params.ids = parentRef.value.selections.map((item) => {
      return item['id']
    })
  }
  const data = await MaterialHistoryApi.exportMaterialHistory(params)
  download.excel(data, val.name)
  parentRef.value.clearTableSelect()
}

/** 初始化 **/
onMounted(async () => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 115
  await getTableTitle()
  getList()
})
</script>
<style lang="scss" scoped>
.btnWrap {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>
